/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ext_dev.h"
#include "pwm_if.h"

#define BEEP_FREQ (1000000000 / 600)

DevHandle g_beepPwmHandle = NULL;
struct PwmConfig g_beepPwmConfig = {
    .duty = 30000,
    .period = 60000,
    .number = 0,
    .polarity = PWM_NORMAL_POLARITY,
    .status = PWM_DISABLE_STATUS,
};

ExtDevCtlRst ExtDevBeepSetFreq(uint32_t ns)
{
    PwmDisable(g_beepPwmHandle);
    if (0 != PwmSetPeriod(g_beepPwmHandle, ns)) {
        LOG_E("Set beep pwm duty failed! ");
        return EXT_DEV_ERROR;
    }
    if (0 != PwmSetDuty(g_beepPwmHandle, ns / 2)) {
        LOG_E("Set beep pwm duty failed! ");
        return EXT_DEV_ERROR;
    }
    PwmEnable(g_beepPwmHandle);

    return EXT_DEV_SUCCESS;
}

static ExtDevCtlRst ExtDevInterSetBeepOff(void)
{
    PwmClose(g_beepPwmHandle);
    return EXT_DEV_SUCCESS;
}

static ExtDevCtlRst ExtDevInterSetBeepOn(void)
{
    if (EXT_DEV_SUCCESS != ExtDevBeepSetFreq(BEEP_FREQ)) {
        LOG_E("ExtDevBeepSetFreq failed!");
        return EXT_DEV_ERROR;
    }
    return EXT_DEV_SUCCESS;
}
/// 蜂鸣器灯初始化
ExtDevCtlRst ExtDevBeepInit(void)
{
    LOG_I("Beep init.");
    g_beepPwmHandle = PwmOpen(0);
    if (NULL == g_beepPwmHandle) {
        LOG_E("open pwm failed!");
    }
    if (0 != PwmSetConfig(g_beepPwmHandle, &g_beepPwmConfig)) {
        LOG_E("config pwm failed!");
    }
    return EXT_DEV_SUCCESS;
}

/// 蜂鸣器控制
ExtDevCtlRst ExtDevBeepSet(ExtDevBeepActDef extDevBeepAct)
{
    if (EXT_DEV_BEEP_ON == extDevBeepAct) {
        if (EXT_DEV_SUCCESS != ExtDevInterSetBeepOn()) {
            return EXT_DEV_ERROR;
        }
    } else if (EXT_DEV_BEEP_OFF == extDevBeepAct) {
        if (EXT_DEV_SUCCESS != ExtDevInterSetBeepOff()) {
            return EXT_DEV_ERROR;
        }
    } else {
        LOG_E("Set beep output failed!");
        return EXT_DEV_ERROR;
    }
    return EXT_DEV_SUCCESS;
}